package com.hrms.config.security.detailservice;

import com.hrms.config.security.exception.CustomerAuthenticationException;
import com.hrms.web.sys_menu.entity.SysMenu;
import com.hrms.web.sys_menu.service.SysMenuService;
import com.hrms.web.sys_user.entity.SysUser;
import com.hrms.web.sys_user.service.SysUserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Title: CustomerUserDetailService
 * @Author zhanji
 * @Package com.hrms.config.security.detailservice
 * @description:
 */
@Component("customerUserDetailService")
public class CustomerUserDetailService implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.loadUser(username);
        if (user ==null){
            throw new CustomerAuthenticationException("用户名错误或用户不存在");
        }
        //查询菜单权限
        List<SysMenu> menuList =null;
        //判断是否为超级管理员
        if(StringUtils.isNotEmpty(user.getIsAdmin()) &&"1".equals(user.getIsAdmin())){
            //是超级管理员
            menuList = sysMenuService.list();
        }else {
            menuList =sysMenuService.selectMenuByUserId(user.getUserId());
        }
        List<String> collect = Optional.ofNullable(menuList).orElse(new ArrayList<>())
            .stream()
            .filter(item -> item!=null && StringUtils.isNotEmpty(item.getCode()))
            .map(item -> item.getCode())
            .collect(Collectors.toList());
        //把权限字段交给springSecurity进行管理
        String[] strings = collect.toArray(new String[collect.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        user.setAuthorities(authorityList);
        return user;
    }
}
